import VirtualList from '@tarojs/components/virtual-list';
import {View} from '@tarojs/components';
import React, {useEffect, useRef, useState} from "react";
import Taro from '@tarojs/taro';
import {getDeviceHeight} from "../../../utils/util";

const Row = React.memo(({ id, index, style, data }) => {
  return (
    <View id={id} className={index % 2 ? 'ListItemOdd' : 'ListItemEven'} style={style}>
      Row {index} : {data[index]}
    </View>
  );
})


function buildData (offset = 0) {
  return Array(100).fill(0).map((_, i) => i + offset);
}

const Index = () => {
  const [data, setData] = useState(buildData(0));
  const [append, setAppend] = useState(0);
  const loading = useRef(false)
  useEffect(()=>{
    Taro.showLoading();
    loading.current = true
    setTimeout(()=>{

      setData(data.concat(buildData(data.length)));
      loading.current = false;
      Taro.hideLoading()
    }, 1000)
  }, [append])
  const listHeight = getDeviceHeight()
  return (
    <View>
      <VirtualList
        className='List'
        height={listHeight}
        itemData={data}
        itemCount={data.length}
        itemSize={100}
        width='100%'
        onScroll={({ scrollDirection, scrollOffset }) => {
          console.log(loading.current, scrollDirection, scrollOffset, (data.length - 5) * 100 + 10)
          if (
            // 避免重复加载数据
            !loading.current &&
            // 只有往前滚动我们才触发
            scrollDirection === 'forward' &&
            // 5 = (列表高度 / 单项列表高度)
            // 100 = 滚动提前加载量，可根据样式情况调整
            scrollOffset > ((data.length - 5) * 100 + 100)
          ) {
            setAppend(append + 1)
          }
        }}
      >
        {Row}
      </VirtualList>
    </View>
  )
}
export default Index;
